<template>
  <div class="app-container menu">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item prop="name">
        <span slot="label">
          菜单名称
          <el-tooltip content="树形表格不支持模糊查询" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </span>
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button  icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!--        <el-button icon="el-icon-question" size="mini" @click="()=>utils.openHelp(this,'')">帮助</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['system:menu:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button

          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:menu:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button

          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"
          v-hasPermi="['system:menu:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button

          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

      <el-table
        ref="table"
        v-if="refreshTable"
        v-loading="loading"
        :data="menuList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @selection-change="handleSelectionChange"
        @row-dblclick="handleUpdate"
        stripe border
        :select-on-indeterminate="true"
        
        @select-all="(selection)=>utils.selectAll(selection,'menuList','table',that)"
        @select="(selection,rows)=>utils.rowSelect(selection,rows,'table',that)"
      >
        <!-- <el-table-column type="index" width="60" align="center"/> -->
        <el-table-column type="selection" width="60" align="center"/>
        <el-table-column prop="name" label="菜单名称"   min-width="150"></el-table-column>
        <el-table-column label="是否显示" align="center" width="150">
          <template slot-scope="scope">
            <span class="label label-danger" v-if="scope.row.visiable=='0'">否</span>
            <span v-else-if="scope.row.visiable=='1'">是</span>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="组件地址"  ></el-table-column>
        <el-table-column prop="perms" label="权限标识"  ></el-table-column>
        <el-table-column prop="orderflag" label="排序"  ></el-table-column>
        <el-table-column label="类型" align="center" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.type=='0'">菜单</span>
            <span v-else-if="scope.row.type=='1'">按钮</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini"
                       v-if="scope.row.type == '0'"
                       type="text"
                       icon="el-icon-plus"
                       @click.stop="handleAdd(scope.row)"
                       v-hasPermi="['system:menu:add']"
            >新增
            </el-button>
            <el-button size="mini"
                       type="text"
                       icon="el-icon-edit"
                       @click.stop="handleUpdate(scope.row)"
                       v-hasPermi="['system:menu:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click.stop="handleDelete(scope.row)"
              v-hasPermi="['system:menu:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" :modal="false" :appendToBody="false" width="600px" :top="scrollTop" v-dialog-drag :close-on-click-modal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row>
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio label="0">菜单</el-radio>
              <el-radio label="1">按钮</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="上级菜单" prop="parentName">
            <el-input v-model="form.parentName" placeholder="请选择上级菜单" :disabled="parentNameDisabled" @click.native="selectedMenuTree()"/>
          </el-form-item>
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入菜单名称"/>
          </el-form-item>

          <el-form-item prop="perms">
            <span slot="label">
              权限标识
              <el-tooltip content="对应web层方法上的权限注解内容，例如 system:ceshi:list" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="50"/>
          </el-form-item>

          <el-form-item v-if="form.type == '0'"  prop="url">
            <span slot="label">
              组件路径
              <el-tooltip content="对应该模块前端页面路径，例如 system/ceshi/index" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.url" placeholder="请输入组件地址" maxlength="50" />
          </el-form-item>
          <el-form-item  v-if="form.type == '0'" prop="isframe">
            <span slot="label">
              是否外链
              <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-radio-group v-model="form.isframe">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.type == '0'"  prop="prop4">
            <span slot="label">
              路由地址
              <el-tooltip content="对应该模块前端页面父级目录名，例如 ceshi" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="form.prop4" placeholder="请输入路由地址"/>
          </el-form-item>


          <el-form-item v-if="form.type == '0'" prop="query">
            <el-input v-model="form.query" placeholder="请输入路由参数" maxlength="255" />
            <span slot="label">
              路由参数
              <el-tooltip content='访问路由的默认传递参数，如：{"id": 1, "name": "eam"}' placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
          </el-form-item>
          <el-form-item v-if="form.type == '0'" prop="assemblyName">
            <el-input v-model="form.assemblyname" placeholder="请输入路由参数" maxlength="255" />
            <span slot="label">
              路由名称
              <el-tooltip content='需要和匹配组件的`name`保持一致' placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
          </el-form-item>
            <el-form-item v-if="form.type == '0'" prop="iscache">
              <span slot="label">
                是否缓存
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-radio-group v-model="form.iscache">
                <el-radio label="1">缓存</el-radio>
                <el-radio label="0">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          <el-form-item v-if="form.type == '0'" label="菜单图标" prop="icon">
            <el-popover
              placement="bottom-start"
              width="460"
              trigger="click"
              @show="$refs['iconSelect'].reset()"
            >
              <IconSelect ref="iconSelect" @selected="selected"/>
              <el-input slot="reference" v-model="form.icon" placeholder="点击选择图标" clearable>
                <svg-icon
                  v-if="form.icon"
                  slot="prefix"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px;width: 16px;"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
              </el-input>
            </el-popover>
          </el-form-item>
          <el-form-item v-if="isOrderflag" label="排序" prop="orderflag">
            <el-input type="text" v-model="form.orderflag" placeholder="请输入排序序号" maxlength="15"/>
          </el-form-item>
          <el-form-item label="是否可见" prop="visiable">
            <el-radio-group v-model="form.visiable">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>



          <el-form-item label="备注" prop="memo">
            <el-input v-model="form.memo" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择上级菜单"
      :visible.sync="openSelectTree"
      @close="closeSelectTree"
      :modal="false"
      :appendToBody="false"
      width="500px" v-dialog-drag
      :top="scrollTop"
    >
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText">
      </el-input>
      <el-tree
        :data="menuList1"
        :check-strictly="true"
        show-checkbox
        check-on-click-node
        :expand-on-click-node="false"
        accordion
        node-key="id"
        ref="tree"
        highlight-current

        :default-checked-keys="[menuTreeId]"
        :default-expanded-keys="[menuTreeId]"
        @check-change="parentModules"
        :props="defaultProps"
        v-if="openSelectTree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="beSure()">保 存</el-button>
        <el-button @click="openSelectTree = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {listMenu, getMenu, delMenu, addMenu, updateMenu} from "@/api/system/menu";
  import IconSelect from "@/components/IconSelect";
  export default {
    name: "Menu",
    components: {IconSelect},
    data() {
      return {
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        //选项id
        ids: [],
        //选项name
        idsName: null,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 菜单表格树数据
        menuList: [],
        menuList1: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 显示状态数据字典
        visibleOptions: [],
        // 菜单状态数据字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          name: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          type: [
            {required: true, message: "菜单类型不能为空", trigger: "blur"}
          ],
          name: [
            {required: true, message: "菜单名称不能为空", trigger: "blur"}
          ],
          prop4: [
            {required: true, message: "路由地址不能为空", trigger: "blur"}
          ],
          perms: [
            {required: true, message: "权限标识不能为空", trigger: "blur"}
          ],
          orderflag: [
            {
              pattern: /^-?[1-9]\d*$/g,
              message: "请输入数字格式",
              trigger: "blur"
            }
          ]
        },
        // 是否禁用上级菜单选项
        parentNameDisabled: false,
        openSelectTree: false,
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        checkedkey: [],
        menuTreeId: null,
        filterText: '',
        //排序显示隐藏字段
        isOrderflag:false,
        // 页面滚动的高度
        scrollTop: null,
        // 是否展开，默认全部折叠
        isExpandAll: false,
        // 重新渲染表格状态
        refreshTable: true,
        that:this
      };
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.idsName = selection.map(item => item.name);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 查询菜单列表 */
      getList() {
        this.loading = true;
        listMenu(this.queryParams).then(response => {
          this.menuList = this.handleTree(response.data, 'id', 'parentid');
          this.loading = false;
        });
      },
      async getList1() {
        await listMenu().then(response => {
          // this.menuList1 = [{name:'主菜单',id:'0',children:this.handleTree(response.data, 'id', 'parentid')}];
          this.menuList1 = this.handleTree(response.data, 'id', 'parentid');
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          parentid: null,
          parentName: null,
          name: null,
          icon: null,
          type: null,
          orderflag: null,
          visiable: "1",
          perms: null,
          prop4: null,
          url:null,
          memo:null,
          isframe: "1",
          iscache: "0",
          query:null,
          assemblyname:null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      async handleAdd(row) {
        this.reset();
        let id = this.ids[0]
        this.parentNameDisabled = false
        if (row) {
          id = row.id
          this.parentNameDisabled = true
        }
        await this.getList1()
        this.isOrderflag=false;
        this.form.type='0';
        this.$nextTick(()=>{
          this.$refs.form.clearValidate();
        })
        if (id) {
          getMenu(id).then(response => {
            this.form.parentid = response.data.id;
            this.form.parentName = response.data.name;
            this.open = true;
            this.title = "添加菜单";
          });
        } else {
          this.open = true;
          this.title = "添加菜单";
        }
      },
      /** 修改按钮操作 */
      async handleUpdate(row) {
        this.reset();
        await this.getList1()
        const id = row.id || this.ids[0];
        getMenu(id).then(response => {
          this.form = response.data;
          this.form.parentid = response.data.parentid;
          this.form.parentName = response.data.parentname;
          this.isOrderflag=true;
          this.open = true;
          this.$nextTick(()=>{
            setTimeout(()=>{
              this.$refs.form.clearValidate();
            })
          })
          this.title = "修改菜单";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateMenu(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addMenu(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const name = row.name || this.idsName;
        const id = row.id || this.ids;
        this.$confirm('是否确认删除名称为"' + name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delMenu(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      selectedMenuTree() {
        if (this.parentNameDisabled) {
          return
        }
        if (this.form.parentid != null) {
          this.menuTreeId = this.form.parentid;
        } else {
          this.menuTreeId = '';
        }
        this.openSelectTree = true;
      },
      beSure() {
        var ids = this.$refs.tree.getCheckedKeys();
        if (ids.length > 0) {
          this.form.parentid = this.$refs.tree.getNode(ids[0]).key;
          this.form.parentName = this.$refs.tree.getNode(ids[0]).label;
          this.$refs.form.clearValidate('parentName');
        }else{
          this.form.parentid = null;
          this.form.parentName = null;
          this.$refs.form.clearValidate('parentName');
        }
        this.openSelectTree = false;
      },
      parentModules(data, checkbox, node) {
        if (checkbox) {
          // 后端返回的node-key不是id，是moduldCode
          this.$refs.tree.setCheckedKeys([data.id]);
          this.$refs.tree.setCurrentKey(data.id);
          this.uniqueValue = this.$refs.tree.getCheckedKeys();
        } else {
          this.uniqueValue = this.$refs.tree.getCheckedKeys();
          if (this.uniqueValue.length == 0) {
            this.uniqueValue = ''
          }
        }
      },
      // filterNode(value, data) {
      //   if (!value) return true;
      //   return data.name.indexOf(value) !== -1;
      // },
      closeSelectTree() {
        this.menuTreeId = null;
        this.filterText = '';
      },

    },
    mounted() {
      this.utils.mounteds(this);
    },
    destroyed() {
      this.utils.destroyeds(this);
    }
  };
</script>
<style>
  /*.menu th .el-checkbox__inner{*/
  /*  display: none;*/
  /*}*/
</style>
